package logic.lbs;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;

/**
 * 定位服务
 *
 * @author 刘宾
 */
public class MyLocation implements AMapLocationListener, Runnable{

	private static final long timeout = 10 * 1000;
	private static LocationManagerProxy locationManager = null;
	private MyLocationListener listener;
	private Context context;
	private Handler handler = new Handler();

	public MyLocation(Context context, MyLocationListener listener) {
		this.listener = listener;
		this.context = context;
	}

	/**
	 * 启用定位服务
	 *
	 * @param time 位置变化通知时间，单位毫秒
	 * @param distance 位置变化通知距离，单位米
	 */
	public void enableLocation(long time, float distance) {
		if (locationManager == null)
			locationManager = LocationManagerProxy.getInstance(context); // 初始化
		locationManager.requestLocationUpdates(LocationProviderProxy.AMapNetwork, time, distance, this);
		handler.postDelayed(this, timeout);
	}

	/**
	 * 关闭定位服务
	 */
	public void disableLocation() {
		if (locationManager != null) {
			locationManager.removeUpdates(this);
			locationManager.destroy();
			locationManager = null;
		}
	}

	public void onLocationChanged(Location arg0) {
	};

	public void onProviderDisabled(String arg0) {
	};

	public void onProviderEnabled(String arg0) {
	};

	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
	};

	public void onLocationChanged(AMapLocation location) {
		disableLocation();
		handler.removeCallbacks(this);
		if (location != null) {
			if (listener != null) {
				listener.locationFinish(location);
			}
		} else{
			if (listener != null) {
				listener.locationFail();
			}
		}
	}

	@Override
	public void run() {
		disableLocation();
		if (listener != null) {
			listener.locationFail();
		}
	}
}
